import os
import platform
import subprocess
import sys
from zoneinfo import available_timezones

from fastmcp import FastMCP

import time


# 实例化fastmcp
mcp = FastMCP("toolBox")

@mcp.tool()
def getTime() -> float:
    """获取当前时间"""
    return time.time()

@mcp.tool()
def getDate() -> str:
    """获取当前日期"""
    return time.strftime("%Y-%m-%d", time.localtime())

@mcp.tool()
def readFile(path: str, startLine: int, deadLine: int) -> str:
    """分行读取文件内容，若文件不存在则返回反馈信息"""
    if not os.path.exists(path):
        return "❌ 文件不存在"
    else:
        with open(path, "r", encoding="utf-8") as f:
            lines = f.readlines()
            return "".join(lines[startLine:deadLine])

@mcp.tool()
def writeFile(path: str, content: str, model:str="w", startLine:int=0) -> str:
    """
    在获取文件前你应该先执行readFile的MCP工具，判断是否存在文件防止覆盖
    写入文件内容需提供写入的起始行数，默认为0；还要提供写入模式，w为覆盖，a为追加"""
    with open(path, model, encoding="utf-8") as f:
        f.seek(startLine)
        f.write(content)
    return "✅ 文件写入成功"

@mcp.tool()
def ls(path: str) -> list:
    """列出目录内容"""
    import os
    if not os.path.exists(path):
        return "❌ 目录不存在"

    return os.listdir(path)

@mcp.tool()
def getComputerInfo() -> dict:
    """获取计算机环境和系统信息
    具体有：
    system: 系统类型
    node: 系统名称
    release: 系统版本
    version: 系统版本信息
    machine: 系统架构
    processor: 处理器类型
    total_memory: 总内存
    cpu_count: CPU核心数
    available_memory: 可用内存
    """
    import platform, psutil
    total_memory = psutil.virtual_memory()
    total_memory = total_memory.total / (1024 * 1024 * 1024)  # 转换为GB
    available_memory = psutil.virtual_memory().available / (1024 * 1024 * 1024)  # 转换为GB
    return {
        "system": platform.system(),
        "node": platform.node(),
        "release": platform.release(),
        "version": platform.version(),
        "machine": platform.machine(),
        "processor": platform.processor(),
        "total_memory": total_memory,
        "cpu_count": psutil.cpu_count(logical=False),
        "available_memory": available_memory
    }

@mcp.tool()
def runCommand(command: str) -> str:
    """执行shell命令并返回输出（隐藏窗口）"""
    try:
        # 创建隐藏窗口的执行标志（仅Windows）
        startup_info = None
        if platform.system() == "Windows":
            startup_info = subprocess.STARTUPINFO()
            startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startup_info.wShowWindow = 0  # SW_HIDE = 0

        # 执行命令
        process = subprocess.Popen(
            command,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            startupinfo=startup_info,
            encoding='utf-8',
            errors='ignore'
        )

        # 等待完成并捕获输出
        output, _ = process.communicate(timeout=30)
        return f"✅ 命令输出：\n{output}"

    except subprocess.TimeoutExpired:
        return "❌ 命令执行超时"
    except Exception as e:
        return f"❌ 执行错误：{str(e)}"

@mcp.tool()
def sendGetRequest(url: str, cookie: str, headers: str) -> str:
    """发送GET请求并返回响应内容"""
    import requests
    try:
        # 解析cookie和headers
        cookie = dict([i.split("=") for i in cookie.split("; ")])
        headers = dict([i.split(": ") for i in headers.split(", ")])
        # 发送请求
        response = requests.get(url, cookies=cookie, headers=headers)
        return f"✅ 请求成功：\n响应文本{response.text}, 响应状态码{response.status_code}"
    except Exception as e:
        return f"❌ 请求失败：{str(e)}"

@mcp.tool()
def sendPostRequest(url: str, cookie: str, headers: str, data: str) -> str:
    """发送POST请求并返回响应内容"""
    import requests
    try:
        # 解析cookie和headers
        cookie = dict([i.split("=") for i in cookie.split("; ")])
        headers = dict([i.split(": ") for i in headers.split(", ")])
        # 发送请求
        response = requests.post(url, cookies=cookie, headers=headers, data=data)
        return f"✅ 请求成功：\n响应文本{response.text}, 响应状态码{response.status_code}"
    except Exception as e:
        return f"❌ 请求失败：{str(e)}"

@mcp.tool()
def getBrowserContent(url: str) -> str:
    """传入一个url，返回该url的HTML内容"""
    from DrissionPage import Chromium
    browser = Chromium(9999)  # 接管9999端口的浏览器
    tab = browser.latest_tab  # 获取最新标签页
    tab.get(url)  # 打开URL
    content = tab.html  # 获取页面HTML内容
    # 进行简单的过滤
    content = content.replace("\n", "").replace("\r", "").replace("\t", "")
    return content  # 返回页面HTML内容

# 获取系统已安装软件
@mcp.tool()
def getInstalledSoftware() -> str:
    """获取系统已安装软件，列表较长，建议AI进行概括式返回"""
    import subprocess
    if platform.system() == "Windows":
        # Windows系统
        try:
            # 获取已安装软件列表
            output = subprocess.check_output(["wmic", "product", "get", "name"]).decode("gbk")
            return f"✅ 获取成功：\n{output}"
        except subprocess.CalledProcessError as e:
            return f"❌ 获取失败：{str(e)}"
    elif platform.system() == "Linux":
        # Linux系统
        try:
            # 获取已安装软件列表
            output = subprocess.check_output(["dpkg", "-l"]).decode("utf-8")
            return f"✅ 获取成功：\n{output}"
        except subprocess.CalledProcessError as e:
            return f"❌ 获取失败：{str(e)}"

# 获取系统启动项
@mcp.tool()
def getStartupItems() -> str:
    """获取系统启动项"""
    import subprocess
    if platform.system() == "Windows":
        # Windows系统
        try:
            # 获取启动项列表
            output = subprocess.check_output(["wmic", "startup", "get", "command"]).decode("gbk")
            return f"✅ 获取成功：\n{output}"
        except subprocess.CalledProcessError as e:
            return f"❌ 获取失败：{str(e)}"
    elif platform.system() == "Linux":
        # Linux系统
        try:
            # 获取启动项列表
            output = subprocess.check_output(["ls", "-l", "/etc/init.d"]).decode("utf-8")
            return f"✅ 获取成功：\n{output}"
        except subprocess.CalledProcessError as e:
            return f"❌ 获取失败：{str(e)}"


if __name__ == "__main__":
    mcp.run()